using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using log4net;
using Sedna.Core.Scheduler.Conditions;

namespace Sedna.Core.Scheduler.Conditions
{
    public class IntervalCondition : BaseCondition
    {
        private ILog log = LogManager.GetLogger(typeof(IntervalCondition));

        private Timer timer;
        private int interval = 20000;
        private TimeSpan idlePeriod;
        private DateTime date;

        public IntervalCondition()
        {
            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(OnElapsed);
        }

        # region Properties

        public int Interval
        {
            set { interval = value; }
        }

        public TimeSpan IdlePeriod
        {
            set { idlePeriod = value; }
        }

        # endregion


        protected override void OnEnable()
        {
            timer.Interval = interval;
            timer.Start();
            date = DateTime.Now;
            log.Info(String.Format("Next run time: {0}", date.Add(idlePeriod)));
        }

        protected override void OnDisable()
        {
            timer.Stop();
        }


        private void OnElapsed(object sender, ElapsedEventArgs e)
        {
            TimeSpan diff = DateTime.Now - date;
            if (diff < idlePeriod)
                return;

            OnTrigger();
            date = DateTime.Now;
            log.Info(String.Format("Next run time: {0}", date.Add(idlePeriod)));
        }
    }
}
